package com.ciaojian.client.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.ciaojian.core.enums.sys.StatusCode;
import com.ciaojian.core.model.vo.ShoppingOrderVo;
import com.ciaojian.client.policy.impl.coupon.CodeDiscount;
import com.ciaojian.client.policy.impl.coupon.MemberCardDiscount;
import com.ciaojian.client.policy.impl.coupon.ShoudanDiscount;
import com.ciaojian.core.constant.RedisConstant;
import com.ciaojian.core.enums.business.GenderEnum;
import com.ciaojian.core.enums.business.HairServiceTypeEnum;
import com.ciaojian.core.enums.business.OrderStatusEnum;
import com.ciaojian.core.enums.business.PayTypeEnum;
import com.ciaojian.core.mapper.*;
import com.ciaojian.core.model.Order;
import com.ciaojian.core.model.*;
import com.ciaojian.core.model.vo.CouponVo;
import com.ciaojian.core.model.vo.OrderVo;
import com.ciaojian.core.service.ICouponDiscount;
import com.ciaojian.core.service.OrderService;
import com.ciaojian.core.util.*;
import com.ciaojian.miniapp.model.request.submessage.TakeCommentMessage;
import com.ciaojian.pay.core.enums.SignType;
import com.ciaojian.pay.wxpay.WxMiniAppApi;
import com.ciaojian.pay.wxpay.WxPayApi;
import com.ciaojian.pay.wxpay.enums.code.RedPackCode;
import com.ciaojian.pay.wxpay.model.bean.WxBean;
import com.ciaojian.pay.wxpay.model.request.TransferModel;
import com.ciaojian.pay.wxpay.model.response.SubMessageSendResponse;
import com.ciaojian.pay.wxpay.model.response.TransferResponse;
import com.ciaojian.pay.wxpay.model.submessage.BaseTemplate;
import com.ciaojian.pay.wxpay.model.submessage.CommissionEnterAccountMessage;
import com.ciaojian.pay.wxpay.model.submessage.TemplateIdEnum;
import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 剪发订单 服务类
 *
 * @author Atlakyn
 */
@Slf4j
@Service
public class OrderServiceImpl extends OrderService<OrderMapper, Order> {
    @Resource
    private MyCouponMapper myCouponMapper;
    @Resource
    private UserStoreMapper userStoreMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private OrderCouponRecordServiceImpl orderCouponRecordService;
    @Resource
    private CouponGrantRecordMapper couponGrantRecordMapper;
    @Resource
    private RedpackSettingServiceImpl redpackSettingService;
    @Resource
    private DistRecordMapper distRecordMapper;
    @Resource
    private CouponCodeServiceImpl couponCodeService;
    @Resource
    private OrderCommissionServiceImpl orderCommissionService;
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private WxBean wxBean;
    @Resource
    private CouponMapper couponMapper;

    /**
     * 获取卡金充值订单详情
     *
     * @param orderId /
     * @return /
     */
    public Map<String, Object> getChargeOrder(Integer orderId) {
        return baseMapper.getChargeOrder(orderId);
    }


    /**
     * <p>1.取号剪发,默认等待15分钟</p>
     * <p>2.取号剪发,获取微信授权为女性,默认等待20分钟</p>
     * <p>3.用户取号染发,默认等待20分钟</p>
     *
     * @param workerId 发型师 id
     * @return 排队列表
     */
    public List<Map<String, Object>> findQueueByWorkerId(Integer workerId) {
        List<Map<String, Object>> queueList = this.baseMapper.findQueueByWorkerId(workerId);
        queueList.forEach(map -> {
            // 开始服务时间
            map.put("startTime", RedisUtil.getKey(RedisConstant.WORKER_START_SERVING_TIME + map.get("id")));
            // 服务类型
            HairServiceTypeEnum type = MapUtil.get(map, "type", HairServiceTypeEnum.class);
            switch (type) {
                case tint:
                    map.put("minute", 20);
                    break;
                case cut:
                    String gender = MapUtil.getStr(map, "gender");
                    if (GenderEnum.female.getDescription().equals(gender)) {
                        map.put("minute", 20);
                    } else {
                        map.put("minute", 15);
                    }
                    break;
                default:
                    map.put("minute", 15);
                    break;
            }
        });
        return queueList;
    }

    public Boolean unlockOrder(Integer orderId) {
        UpdateWrapper<Order> wrapper = new UpdateWrapper<>();
        wrapper.set("status", 2)
                .eq("id", orderId)
                .eq("status", 21)
        ;
        return this.update(wrapper);
    }

    /**
     * 查询重复的优惠券订单
     *
     * @param couponId 优惠券类型
     * @param userId   用户订单
     * @return 如果 15 分钟内提交过订单则返回该笔订单,否则返回 null
     */
    @Transactional(rollbackFor = Exception.class)
    public Order getRepeat(Integer couponId, Integer userId, Integer orderType) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("coupon_id", couponId)
                .eq("user_id", userId)
                .eq("status", 21)
                .eq("order_type", orderType);
        Order order = new Order().selectOne(queryWrapper);
        if (order == null) {
            return null;
        }

        // 如果订单创建时间比当前时间的 30 分钟前还要早,表示订单已经过期了
        if (DateUtil.compare(order.getAddTime(), DateUtil.offset(new Date(), DateField.MINUTE, -15)) <= 0) {
            // 删除订单
            order.deleteById();
            return null;
        }
        return order;
    }


    /**
     * 是否未买过
     *
     * @return 没买过返回 true
     */
    public Boolean checkNotSold(Integer couponId, Integer userId) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("coupon_id", couponId)
                .eq("user_id", userId)
                .eq("status", 5)
                .eq("order_type", 5)
                .last("limit 1");
        Integer count = new Order().selectCount(queryWrapper);
        return count == 0;
    }

    /**
     * 支付回调业务
     *
     * @param order 订单
     */
    public void payNotify(Order order) {
        //更新订单状态（status改为3：已支付 ）
        order.setStatus(OrderStatusEnum.paid);
        order.setPayType("微信支付");
        order.setPayTime(new Date());
        order.setPayTotal(order.getTotal());
//        this.setCustomerType(order);

        // 更新券码为已使用
        List<OrderCouponRecord> orderCouponRecordList = orderCouponRecordService.lambdaQuery()
                .eq(OrderCouponRecord::getOrderId, order.getId()).list();
        orderCouponRecordList.forEach(orderCouponRecord -> myCouponMapper.updateCodeStatus(orderCouponRecord.getCouponCode(), 2));
        // 设置在一天的结束时无效化缓存
        RedisUtil.expireAt(RedisConstant.USED_DOUYIN_ORDER + order.getUserId(), DateUtil.endOfDay(new Date()));
        // 剪发新增提成记录
        orderCommissionService.insert(order);

        // 会员优惠
        QueryWrapper<MemberDiscount> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no", order.getOrderNo());
        MemberDiscount memberDiscount = new MemberDiscount().selectOne(queryWrapper);
        if (memberDiscount != null) {
            // 支付成功在 member_discount 中设置 orderId
            memberDiscount.setOrderId(order.getId());
            memberDiscount.updateById();
        }

        // 如果已有数据则更新,否则插入(用户对门店的消费记录,不是订单)
        insertOrUpdate(order);
        order.updateById();
        LogUtil.writePayLog(">>>微信支付回调>>>修改后的订单={}", new Order().selectById(order.getId()));

        // 首次消费,为分销员发送微信红包
        firstConsume2(order);
    }

    /**
     * 分销员业务
     * <p>分销员分销给新用户,新用户消费后给分销员发放佣金</p>
     * <strong>此业务上线后,{@link #firstConsume(Order)} 业务将暂停</strong>
     *
     * @param order 订单
     */
    @Async
    public void firstConsume2(Order order) {
        Optional<DistRecord> optional = Optional.ofNullable(distRecordMapper.getByTargetId(order.getUserId()));
        optional.ifPresent(distRecord -> {
            // d_dist_record set orderId 为消费的订单
            if (order.getStatus() != OrderStatusEnum.servicing
                    && order.getStatus() != OrderStatusEnum.wait_pay
                    && order.getCustomerType() == 3) {
                // 查找分销记录

                distRecord.setOrderId(order.getId());
                Integer recordCount = orderMapper.getRecordCount(distRecord.getDistId());
                // 1次 = 10
                // 2次 = 10
                // 3次 = 20
                // 4次 = 10  以此类推
                recordCount = recordCount + 1;
                if (recordCount<4) {
                    switch (recordCount) {
                        case 1:
                            distRecord.setMoney(1000);
                            break;
                        case 2:
                            distRecord.setMoney(1000);
                            break;
                        case 3:
                            distRecord.setMoney(2000);
                            break;
                        default:
                            break;
                    }
                }else {
                    recordCount = recordCount % 3;
                    switch (recordCount) {
                        case 1:
                            distRecord.setMoney(1000);
                            break;
                        case 2:
                            distRecord.setMoney(1000);
                            break;
                        case 0:
                            distRecord.setMoney(2000);
                            break;
                        default:
                            break;
                    }
                }

                // 微信企业转账
                Map<String, Object> params = TransferModel.builder()
                        .nonce_str(RandomUtil.randomString(32))
                        .mchid(wxBean.getMchId())
                        .mch_appid(wxBean.getAppId())
                        .partner_trade_no(order.getOrderNo())
                        .openid(UserUtil.getOpenId(distRecord.getDistId()))
                        .check_name(TransferModel.CheckType.NO_CHECK)
                        .amount(String.valueOf(distRecord.getMoney()))
                        .desc("分销员分佣奖励")
                        .build()
                        .createSign(wxBean.getAppSecret(), SignType.MD5, false);
                TransferResponse response = WxPayApi.transfers(params, wxBean.getCertPath(), wxBean.getCertPass());

                if (response.getResult_code().equals(RedPackCode.FAIL.getCode())) {
                    System.err.println(response.getErr_code() + ":" + response.getErr_code_des());
                    log.info(response.getErr_code() + ":" + response.getErr_code_des());
                }
                distRecord.setRemark(RedPackCode.FAIL.getDesc());
                distRecordMapper.updateById(distRecord);
            }
        });
    }

    /**
     * 首次消费,为送券人发送红包
     *
     * @param order 订单
     */
    @Async
    public void firstConsume(Order order) {
        RedpackSetting redpackSetting = redpackSettingService.getById(1);
        // 如果用户首次消费,则为送券人发送微信红包
        if (order.getStatus() != OrderStatusEnum.servicing && order.getStatus() != OrderStatusEnum.wait_pay && order.getCustomerType() == 3 && !redpackSetting.getIsClose()) {
            // 查找送券人
            Integer source = couponGrantRecordMapper.getSource(order.getUserId(), 430);
            if (source != null) {
                // 新增发送红包记录
                new SendRedpackRecord()
                        .setMchBillNo(order.getOrderNo())
                        .setUserId(source)
                        .setStatus(0)
                        .setAmount(redpackSetting.getTotalAmount())
                        .insert();
                try {
                    // 发送订阅消息
                    BaseTemplate baseTemplate = BaseTemplate.builder(TemplateIdEnum.COMMISSION_ENTER_ACCOUNT)
                            .touser(UserUtil.getOpenId(source))
                            .data(CommissionEnterAccountMessage.builder()
                                    .thing5("分享用户" + order.getUserId() + "已消费")
                                    .amount6("最高可达99元")
                                    .time9(new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss").format(new Date()))
                                    .build());
                    SubMessageSendResponse response = WxMiniAppApi.subscribeMessageSend(baseTemplate);
                    System.err.println(response.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error(e.getMessage());
                }
            }
        }
    }

    /**
     * 如果已有数据则更新,否则插入(用户对门店的消费记录)
     *
     * @param order 订单
     */
    private void insertOrUpdate(Order order) {
        // 插入用户对门店的消费记录
        QueryWrapper<UserStore> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", order.getUserId())
                .eq("store_id", order.getStoreId())
                .last("limit 1");
        UserStore userStore = userStoreMapper.selectOne(queryWrapper);
        if (userStore == null) {
            userStore = new UserStore();
            userStore.setUserId(order.getUserId());
            userStore.setStoreId(order.getStoreId());
            userStore.setStoreName(order.getStoreName());
            userStore.insert();
        } else {
            userStore.updateById();
        }
    }

    public BigDecimal calDiscount(Order order, String code, String type, Integer memberDiscountId, BigDecimal money, Integer userIdOfOrder) throws JsonProcessingException {
        BigDecimal amount;
        // 首单优惠 id 不为空
        if (memberDiscountId != null) {
            LogUtil.writeBusinessLog(">>>calDiscount>>>用户[{}]有首单优惠id[{}]", userIdOfOrder, memberDiscountId);
            // 首单优惠
            ICouponDiscount<Map<String, Object>> couponDiscount = ApplicationContextHelper.getBean(ShoudanDiscount.class);
            Map<String, Object> shoudanMap = new HashMap<>(2);
            shoudanMap.put("memberDiscountId", memberDiscountId);
            shoudanMap.put("userIdOfOrder", userIdOfOrder);
            amount = couponDiscount.discountAmount(shoudanMap, money);
        }
        // 使用优惠券
        else if (StrUtil.isNotEmpty(code)) {
            LogUtil.writeBusinessLog(">>>calDiscount>>>用户[{}]有优惠券码[{}]", userIdOfOrder, code);
            ICouponDiscount<Map<String, Object>> codeDiscount = ApplicationContextHelper.getBean(CodeDiscount.class);
            Map<String, Object> codeMap = new HashMap<>(2);
            codeMap.put("code", code);
            codeMap.put("userId", userIdOfOrder);
            codeMap.put("order", order);
            amount = codeDiscount.discountAmount(codeMap, money);
        }
        // 会员折扣
        else {
            LogUtil.writeBusinessLog(">>>calDiscount>>>用户[{}]有会员折扣", userIdOfOrder);
            ICouponDiscount<Map<String, Object>> memberCardDiscount = ApplicationContextHelper.getBean(MemberCardDiscount.class);
            Map<String, Object> memberMap = new HashMap<>(2);
            memberMap.put("userId", userIdOfOrder);
            memberMap.put("type", type);
            amount = memberCardDiscount.discountAmount(memberMap, money);
        }
        return amount;
    }

    @Transactional(rollbackFor = Exception.class)
    public BigDecimal calDiscountV2(Order order, List<String> codes, String type, Integer memberDiscountId, BigDecimal money, Integer userIdOfOrder) throws JsonProcessingException {
        BigDecimal amount;
        // 首单优惠 id 不为空
        if (memberDiscountId != null) {
            LogUtil.writeBusinessLog(">>>calDiscount>>>用户[{}]有首单优惠id[{}]", userIdOfOrder, memberDiscountId);
            // 首单优惠
            ICouponDiscount<Map<String, Object>> couponDiscount = ApplicationContextHelper.getBean(ShoudanDiscount.class);
            Map<String, Object> shoudanMap = new HashMap<>(2);
            shoudanMap.put("memberDiscountId", memberDiscountId);
            shoudanMap.put("userIdOfOrder", userIdOfOrder);
            amount = couponDiscount.discountAmount(shoudanMap, money);
        }
        // 使用优惠券
        else if (CollUtil.isNotEmpty(codes)) {
            LogUtil.writeBusinessLog(">>>calDiscount>>>用户[{}]有优惠券码[{}]", userIdOfOrder, codes.toString());
            ICouponDiscount<Map<String, Object>> codeDiscount = ApplicationContextHelper.getBean(CodeDiscount.class);
            Map<String, Object> codeMap = new HashMap<>(2);
            codeMap.put("code", codes);
            codeMap.put("userId", userIdOfOrder);
            codeMap.put("order", order);
            amount = codeDiscount.discountAmount(codeMap, money);
        }
        // 会员折扣
        else {
            LogUtil.writeBusinessLog(">>>calDiscount>>>用户[{}]有会员折扣", userIdOfOrder);
            ICouponDiscount<Map<String, Object>> memberCardDiscount = ApplicationContextHelper.getBean(MemberCardDiscount.class);
            Map<String, Object> memberMap = new HashMap<>(2);
            memberMap.put("userId", userIdOfOrder);
            memberMap.put("type", type);
            amount = memberCardDiscount.discountAmount(memberMap, money);
        }
        return amount;
    }

//    @Transactional(rollbackFor = Exception.class)
//    public BigDecimal calDiscountV3(Order order, Coupon coupon, DiscountTypeEnum discountType) {
//        DiscountCalculator discountCalculator = DiscountCalculatorFactory.get(discountType);
//        discountCalculator.calculate()
//    }

    @Transactional(rollbackFor = Exception.class)
    public void freeOrder(Order order, List<String> codes, String type, Integer memberDiscountId) throws JsonProcessingException {
        // 订单id
        Integer orderId = order.getId();
        // 订单总价
        BigDecimal money = order.getTotal();
        // 优惠后的价格
        BigDecimal amount = this.calDiscountV2(order, codes, type, memberDiscountId, money, order.getUserId());
        BigDecimal discount = money.subtract(amount);
        LogUtil.writeBusinessLog(">>>免单接口 订单信息>>>orderId={},money={},amount={},discount={}", orderId, money, amount, discount);

        UpdateWrapper<Order> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", orderId);

        // 优惠券不为空
        if (CollUtil.isNotEmpty(codes)) {
            codes.forEach(code -> {
                CouponVo couponVo = myCouponMapper.getCouponByCode(code);
                order.setCouponCode(couponVo.getCode());
                order.setCouponId(couponVo.getId());
                myCouponMapper.getCouponByCode(code);
                // 使用优惠券记录
                new OrderCouponRecord()
                        .setUserId(order.getUserId())
                        .setOrderId(order.getId())
                        .setCouponId(couponVo.getId())
                        .setCouponCode(couponVo.getCode())
                        .setCouponTitle(couponVo.getTitle())
                        .insert();
                // 该优惠券状态改为已使用
                myCouponMapper.updateCodeStatus(code, 2);
                // 插入优惠记录
                DiscountRecord discountRecord = DiscountRecord.builder()
                        .orderId(orderId)
                        .type(0)
                        .amount(discount)
                        .describe(String.format("使用了 %s 优惠券优惠了 %s 元", codes, discount))
                        .build();
                discountRecord.insert();
                // 用户使用了抖音券, 用Redis缓存, 如果用户后续购买了会员权益, 会赠送相应的优惠券
                couponCodeService.usedDouyinCouponCode(couponVo, order.getUserId());
                // 剪发新增提成记录
                orderCommissionService.insert(order);
            });
        }
        order.updateById();

        // 会员优惠
        MemberDiscount memberDiscount = new MemberDiscount().selectById(memberDiscountId);
        if (memberDiscount != null) {
            // 支付成功在 member_discount 中设置 orderId
            memberDiscount.setOrderId(orderId);
            memberDiscount.updateById();

            // 插入优惠记录
            DiscountRecord discountRecord = DiscountRecord.builder()
                    .orderId(orderId)
                    .type(1)
                    .amount(discount)
                    .describe(String.format("使用了首单优惠 %s 优惠了 %s 元", memberDiscountId, discount))
                    .build();
            discountRecord.insert();
        }
        order.setAddTime(new Date());

        this.setCustomerType(order);
        // 顾客当前订单之前已完成和已支付的订单数
//        Integer count = this.countNumberOfComplete(order);
        // 支付成功 修改订单为已支付状态
        updateWrapper.set("status", 3)
                .set("pay_type", PayTypeEnum.FREE.getDescription())
                .set("pay_time", new Date())
                .set("pay_total", BigDecimal.ZERO)
                .set("coupon_total", discount);
        // 0次 = 未消费用户
        // 1次 = 首次消费用户
        // 2次-3次 = 生客
        // 4次-5次 = 熟客
        // 5次+ = 深度用户
//        switch (count + 1) {
//            case 1:
//                updateWrapper.set("customer_type", 3);
//                break;
//            case 2:
//            case 3:
//                updateWrapper.set("customer_type", 0);
//                break;
//            case 4:
//            case 5:
//                updateWrapper.set("customer_type", 1);
//                break;
//            default:
//                updateWrapper.set("customer_type", 2);
//                break;
//        }
        this.update(updateWrapper);
        // 首次消费,为送券人发送微信红包
//        firstConsume(order);

        // 首次消费,为分销员发送微信红包
        firstConsume2(order);

        try {
            User user = userMapper.selectById(order.getUserId());
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            String expiredTime = simpleDateFormat.format(new Date());

            com.ciaojian.miniapp.model.request.submessage.BaseTemplate baseTemplate = com.ciaojian.miniapp.model.request.submessage.BaseTemplate.builder(com.ciaojian.miniapp.model.request.submessage.TemplateIdEnum.COMMENT_TO_EXPIRE)
                    .touser(user.getOpenid())
                    .data(TakeCommentMessage.builder()
                            .thing1(order.getStoreName())
                            .time2(expiredTime)
                            .thing3("反馈评价可随机获取剪发券奖励!")
                            .build()
                    );
            com.ciaojian.miniapp.model.response.SubMessageSendResponse response1 = com.ciaojian.miniapp.api.WxMiniAppApi.subscribeMessageSend(baseTemplate);
            if (response1.getErrcode() == 0) {

            } else {
                LogUtil.writeBusinessLog("提醒评价通知失败CommentExpired: {}", response1.getErrmsg());
            }
        } catch (Exception e) {
            LogUtil.writeErrorLog(e.getMessage());
        }
    }

    /**
     * 等待时间
     *
     * @param workerId 理发师id
     * @param orderNo  订单号
     * @return 需要等待的人数和时间
     */
    public Map<String, Integer> minuteTake(Integer workerId, String orderNo) {
        List<Map> beforeOrderList = baseMapper.findBeforeOrder(workerId, orderNo);

        return minuteTake(beforeOrderList);
    }

    /**
     * 等待时间订单排队倒计时
     *
     * @param workerId 理发师id
     * @param orderNo  订单号
     * @return 需要等待的人数和时间
     */
    public Map<String, Integer> minuteTakes(Integer workerId, String orderNo) {
        List<Map> beforeOrderList = baseMapper.findBeforeOrder(workerId, orderNo);

        return minuteTakes(beforeOrderList);
    }

    public List<OrderVo> getOrderVo(Integer id) {
        return getBaseMapper().getDOrderVo(id);
    }


    public List<ShoppingOrderVo> getShoppingOrder(Integer userId){

        return orderMapper.getShoppingOrder(userId);
    }


    public Result getShoppingOrderInfo(Integer orderId, Integer userId){
        ShoppingOrderVo shoppingOrderInfo = orderMapper.getShoppingOrderInfo(orderId);

        if (!shoppingOrderInfo.getUserId().equals(userId)){
            return Result.fail(StatusCode.FAIL,"系统错误");
        }


        //卡券列表
        List<Coupon> couponList = new ArrayList<>();
        String[] coupons =  shoppingOrderInfo.getCoupons().split(",");
        for (String coupon : coupons) {
            Coupon couponOne = couponMapper.selectById(coupon);
            couponList.add(couponOne);
        }
        shoppingOrderInfo.setCouponList(couponList);

        return Result.ok(shoppingOrderInfo);
    }


    public Result getHairperiod(Integer userId,Date month) throws ParseException {
        //剪发日期
        Calendar calendarNew = Calendar.getInstance();
        calendarNew.setTime(month);
        calendarNew.add(Calendar.MONTH, -1);
        Date lastMonth = calendarNew.getTime();

        Calendar calendarNew2 = Calendar.getInstance();
        calendarNew2.setTime(month);
        calendarNew2.add(Calendar.MONTH, +1);
        Date nextMonth = calendarNew2.getTime();

        List<String> hairTimes  = orderMapper.getHairTime(userId, lastMonth,nextMonth);


        //推荐剪发日期

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        String format = null;
        String format1 = null;
        List<String> nextHairTimes = new ArrayList<>();
        if (hairTimes.size()!=0) {
            String time1 = hairTimes.get(hairTimes.size() - 1);
            Date parse = dateFormat.parse(time1);
            calendar.setTime(parse);
            calendar.add(Calendar.MONTH, +1);
            parse = calendar.getTime();
            Date nextHairTime = parse;
            Date date = new Date();
            if (nextHairTime.getTime()<date.getTime()){
                calendar.add(Calendar.DAY_OF_MONTH, +1);
                nextHairTime = calendar.getTime();
                format1 = dateFormat.format(nextHairTime);
                nextHairTimes.add(format1);
                format = dateFormat.format(date);
            }else {
                if (com.ciaojian.core.util.DateUtil.judgeTimeIsToday(nextHairTime)) {
                    calendar.add(Calendar.DAY_OF_MONTH, +1);
                    nextHairTime = calendar.getTime();
                    format1 = dateFormat.format(nextHairTime);
                    nextHairTimes.add(format1);
                }
                format = dateFormat.format(nextHairTime);
            }
        }else {
            Date date = new Date();
            calendar.setTime(date);
            calendar.add(Calendar.DAY_OF_MONTH, +1);
            Date nextHairTime = calendar.getTime();
            nextHairTime = calendar.getTime();
            format = dateFormat.format(nextHairTime);
            format1 = dateFormat.format(date);
            nextHairTimes.add(format1);
        }
        nextHairTimes.add(format);

        //服务过发型师人数
        Integer hairWorkerCount = orderMapper.getHairWorkerCount(userId);

        //剪发次数
        Integer serviceCount = orderMapper.getServiceCount(userId);

        Date addTime = userMapper.getAddTime(userId);
        Date date = new Date();
        int startTime = 0;
        try {
            startTime = com.ciaojian.core.util.DateUtil.differentDays(addTime, date);
        }catch (Exception e){

        }
        Map<String, Object> map = new HashMap<>(7);
        map.put("hairTimes", hairTimes);
        map.put("hairWorkerCount", hairWorkerCount);
        map.put("serviceCount", serviceCount);
        map.put("startTime", startTime);
        map.put("nextHairTimes", nextHairTimes);


        return Result.ok(map);

    }
}
